package geradatawarehouse.dao.postgres;

import geradatawarehouse.bean.Curso;
import geradatawarehouse.dao.postgres.abs.PostgresDAO;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class CursoPostgresDAO extends PostgresDAO {
	private static final String TRUNCATE_CURSO = "truncate curso";

	protected CursoPostgresDAO() throws IOException {
		super();
	}

	private void fillTable(final List<Curso> lista, final Connection conn)
			throws SQLException {

		if (lista.size() == 0) {
			return;
		}

		final StringBuilder queryBuilder = new StringBuilder();

		queryBuilder
				.append("INSERT INTO curso(codigo, cod_unidade, nome, ano_sem) ");
		queryBuilder.append(" VALUES ");

		for (final Curso curso : lista) {
			queryBuilder.append("(");
			queryBuilder.append(curso.getCodigo());
			queryBuilder.append(", '");
			queryBuilder.append(this.escape(curso.getCodUnidade()));
			queryBuilder.append("', '");
			queryBuilder.append(this.escape(curso.getNome()));
			queryBuilder.append("', ");
			queryBuilder.append(curso.getAnoSem());
			queryBuilder.append(")");
			queryBuilder.append(", ");
		}

		String query = queryBuilder.toString();

		query = query.substring(0, query.length() - ", ".length());

		final Statement smt = conn.createStatement();

		smt.executeUpdate(query);

	}

	public void replaceAll(final List<Curso> lista) throws SQLException {

		Connection conn = null;

		try {
			conn = this.buildConnection();

			conn.setAutoCommit(false);

			this.truncateTable(conn);

			this.fillTable(lista, conn);

			conn.commit();

		} catch (final SQLException e) {
			conn.rollback();
			throw e;
		} finally {
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
		}

	}

	/**
	 * @param conn
	 * @throws SQLException
	 */
	private void truncateTable(final Connection conn) throws SQLException {
		final Statement smt = conn.createStatement();

		smt.executeUpdate(CursoPostgresDAO.TRUNCATE_CURSO);
	}
}
